package com.ehotting.edsta.circuitDesign;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHelper implements ApplicationContextAware {
    private static Logger logger = LoggerFactory.getLogger(SpringContextHelper.class);
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext not inject,please in applicationContext.xml define SpringContextHelper");
        }
    }



    public static String getDefaultMessage(String code, int length) {
        StringBuffer sb = (new StringBuffer()).append('[').append(code).append("]Undefined");
        if (length > 0) {
            for(int i = 0; i < length; ++i) {
                sb.append("_{" + i + "}");
            }
        }

        return sb.toString();
    }

}
